package com.leonardo.lengthexample;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import MAR.Core.Reflector;

import com.leonardo.beanme.model.BeanForm;

public class ExampleMidlet extends MIDlet implements CommandListener {

	protected Display display;
	private BeanForm form;
	
	public ExampleMidlet() throws Exception {
		this.display = Display.getDisplay(this);
		
		LengthBean bean = new LengthBean();
		System.out.println(bean instanceof Reflector);
		Reflector reflector = (Reflector) bean;
		
		/*Mode 1: empty default*/
		this.form = new BeanForm(LengthBean.class);
		/*Mode 2: empty customized*/
//		this.form = new BeanForm(LengthBean.class, "lengthbean");

//		LengthBean bean = new LengthBean();
//		bean.setBool(new Boolean(false));
//		bean.setHasLength("Init");
//		bean.getCombo().select(2);
//		bean.getRadio().select(1);
		/*Mode 3: filled default*/
//		this.form = new BeanForm(bean);
		/*Mode 4: filled customized*/
//		this.form = new BeanForm(bean, "lengthbean");
		
		/*
		 Try change the "lengthbean" id to "lengthbean2", "lengthbean3"
		 and "lengthbean4", this last should produce an error  
		 */
	}
	
	protected void destroyApp(boolean unconditional) {
		notifyDestroyed();
	}

	protected void pauseApp() {}


	protected void startApp() throws MIDletStateChangeException {
		form.addCommand(new Command("Recover bean", Command.OK, 0));
		form.addCommand(new Command("Back", Command.BACK, 1));
		form.addCommand(new Command("Clear", Command.CANCEL, 1));
		form.addCommand(new Command("Exit", Command.EXIT, 0));
		form.setCommandListener(this);
		
		this.display.setCurrent(form);		
	}

	public void commandAction(Command c, Displayable d) {
		switch(c.getCommandType()) {
		case Command.BACK:
		case Command.EXIT:
			destroyApp(true);
			break;
		case Command.CANCEL:
			form.clear();
			break;
		case Command.OK:
			try {
				LengthBean bean = (LengthBean) form.getBean();
				bean.printAll();
			} catch (Exception ex) {
				ex.printStackTrace();
			}	
			break;
		}
	}

}
